package server

import (
	"context"
	"encoding/json"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/api"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/messages/mgr_message"
	mgr_chat2 "longmen/server/internal/rpc/tencentim/mgr_chat"
	"longmen/server/internal/rpc/tencentim/room_event"
	"longmen/server/pkg/common/lib/bytesconv"
	"longmen/server/pkg/common/sdk/tx"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"strconv"
	"time"
)

// GetMgrChats 获取聊天列表
func (s *TencentIM) GetMgrChats(ctx context.Context, req *pb.GetMgrChatsReq) (resp *pb.GetMgrChatsResp, err error) {
	resp = &pb.GetMgrChatsResp{
		MgrChatList: []*pb.MgrChatList{},
	}

	managerUser, _ := db_live.GetLiveRoomManagerParam(map[string]interface{}{"mgrid": req.UserId})
	isMgr := managerUser.Id > 0

	whereField := "mgr_id"
	if !isMgr {
		whereField = "user_id"
	}

	chats, err := db_main.GetMgrChatList(map[string]interface{}{
		whereField: req.GetUserId(),
	}, "", 0, 0)
	if err != nil {
		return
	}

	userIds := []int{int(req.UserId)}
	for _, v := range chats {
		if isMgr {
			userIds = append(userIds, v.UserId)
		} else {
			userIds = append(userIds, v.MgrId)
		}
	}
	users, err := db_main.GetUsersParam(map[string]interface{}{
		"id": map[string]interface{}{
			"in": userIds,
		},
	}, "", 0, 0)
	if len(users) <= 0 {
		return
	}

	userMp := map[int]*models_main.User{}
	for k, v := range users {
		userMp[v.Id] = users[k]
	}

	for _, v := range chats {
		role := 0
		if isMgr {
			role = 1
		}
		chatUserId := func() uint32 {
			if isMgr {
				return uint32(v.UserId)
			}
			return uint32(v.MgrId)
		}()
		user, ok := userMp[int(chatUserId)]
		if !ok {
			continue
		}
		resp.MgrChatList = append(resp.MgrChatList, &pb.MgrChatList{
			MgrId:         uint32(v.MgrId),
			MgrChatUserId: uint32(v.UserId),
			Avatar:        user.Avatar,
			NickName:      user.NickName,
			Role:          uint32(role),
			UnreadNum:     uint32(cache.GetMgrChatUserReadNum(int(req.UserId), int(chatUserId))),
		})
	}
	return
}

// GetMgrChatHistory 获取历史记录
func (s *TencentIM) GetMgrChatHistory(ctx context.Context, req *pb.GetMgrChatHistoryReq) (resp *pb.GetMgrChatHistoryResp, err error) {
	//判断发送者身份, 并且插入新的聊天列表记录
	_, mgrChat, err := mgr_chat2.CheckUserMgr(int(req.SelfUserId), int(req.UserId))
	if err != nil {
		return nil, err
	}

	//查询删除记录
	mDel, _ := db_main.GetMgrChatDelete(map[string]interface{}{
		"user_id":      req.SelfUserId,
		"chat_user_id": req.UserId,
	})
	delStamp := int64(0)
	if mDel.Id > 0 {
		delStamp = mDel.CreateStamp
	}

	defer cache.ResetMgrChatUserReadNum(int(req.SelfUserId), int(req.UserId))
	history, total := mgr_chat2.GetHistory(mgr_chat2.GetChatId(mgrChat), int(req.Page), int(req.Limit), delStamp)
	if err != nil {
		return
	}

	mgrHis := []*pb.MgrChatHistory{}
	for _, v := range history {
		mgrHis = append(mgrHis, &pb.MgrChatHistory{
			ChatId:      v.ChatId,
			SenderUid:   uint32(v.SenderUid),
			ReceiveUid:  uint32(v.ReceiveUid),
			Avatar:      v.Avatar,
			Nickname:    v.Nickname,
			Content:     v.Content,
			SendTime:    v.SendTime,
			Role:        uint32(v.Role),
			ImageUrl:    v.ImageUrl,
			ImageWidth:  uint32(v.ImageWidth),
			ImageHeight: uint32(v.ImageHeight),
			TextType:    uint32(v.TextType),
			Id:          v.Id,
		})
	}
	resp = &pb.GetMgrChatHistoryResp{
		MgrChatHistory: mgrHis,
		Total:          total,
	}
	return
}

// DelMgrChat 删除聊天记录
func (s *TencentIM) DelMgrChat(ctx context.Context, req *pb.DelMgrChatReq) (resp *pb.DelMgrChatResp, err error) {
	resp = &pb.DelMgrChatResp{
		IsSucceed: false,
		Tips:      "",
	}

	_, chat, err := mgr_chat2.CheckUserMgr(int(req.SelfUserId), int(req.UserId))
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	err = db_main.DeleteMgrChat(chat)
	if err != nil {
		return
	}

	err = db_main.InsertMgrChatDelete(&models_main.MgrChatDelete{
		CreateStamp: time.Now().Unix(),
		UserId:      int(req.SelfUserId),
		ChatUserId:  int(req.UserId),
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}
	resp = &pb.DelMgrChatResp{
		IsSucceed: true,
		Tips:      "OK",
	}
	return
}

// DelMgrChatHistory 清空聊天历史
func (s *TencentIM) DelMgrChatHistory(ctx context.Context, req *pb.DelMgrChatHistoryReq) (resp *pb.DelMgrChatHistoryResp, err error) {
	resp = &pb.DelMgrChatHistoryResp{
		IsSucceed: false,
		Tips:      "",
	}

	err = db_main.InsertMgrChatDelete(&models_main.MgrChatDelete{
		CreateStamp: time.Now().Unix(),
		UserId:      int(req.SelfUserId),
		ChatUserId:  int(req.UserId),
	})
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	resp = &pb.DelMgrChatHistoryResp{
		IsSucceed: true,
		Tips:      "OK",
	}
	return
}

// DelMgrSingleMsg 删除单条消息
func (s *TencentIM) DelMgrSingleMsg(ctx context.Context, req *pb.DelMgrSingleMsgReq) (resp *pb.DelMgrSingleMsgResp, err error) {
	resp = &pb.DelMgrSingleMsgResp{}

	h, err := mgr_chat2.GetFromEs(req.MsgId)
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	err = mgr_chat2.DeleteHistory(req.MsgId)
	if err != nil {
		resp.Tips = err.Error()
		return
	}

	if len(h.ImageUrl) > 0 {
		err = tx.DeleteObject(h.ImageUrl)
		if err != nil {
			global.Log.Error(err)
		}
	}

	SendUser(h)

	resp.IsSucceed = true
	return
}

// SendUser 发送消息给前端
func SendUser(h *mgr_chat2.History) {
	typ := messages2.MgrMessageReplyType
	resp, _ := json.Marshal(mgr_message.ReplyMessage{
		IncomingMessage: messages2.IncomingMessage{
			Type:    &typ,
			GroupId: h.SenderUid,
		},
		Id:          h.Id,
		ChatId:      h.ChatId,
		Content:     h.Content,
		SenderUid:   h.SenderUid,
		ReceiveUid:  h.ReceiveUid,
		Avatar:      h.Avatar,
		Nickname:    h.Nickname,
		SendTime:    h.SendTime,
		Role:        h.Role,
		TextType:    mgr_chat2.MgrHistoryDeleteType,
		ImageUrl:    h.ImageUrl,
		ImageWidth:  h.ImageWidth,
		ImageHeight: h.ImageHeight,
	})
	b, _ := json.Marshal(resp)
	err := imsdk.GetSdk().SendUser(strconv.Itoa(h.ReceiveUid), bytesconv.BytesToString(b))
	if err != nil {
		global.Log.Error(err)
	}
	//通知
	err = imsdk.GetSdk().SendUser(strconv.Itoa(h.SenderUid), bytesconv.BytesToString(b))
	if err != nil {
		global.Log.Error(err)
	}
}

func (s *TencentIM) WriteChatHistory(ctx context.Context, req *pb.WriteChatHistoryReq) (resp *pb.WriteChatHistoryResp, err error) {
	err = api.GetAPI().ChatHistory(req.GetContent(), int(req.GetUid()), int(req.GetRoomId()), req.GetChatId())
	resp = &pb.WriteChatHistoryResp{}
	room_event.GetChatHistory(int(req.GetRoomId())).AppendChatHistory(messages2.ChatHistory{
		Id:         req.GetChatId(),
		Content:    req.GetContent(),
		UserId:     int64(req.GetUid()),
		ClientName: req.GetClientName(),
		Level:      int(req.GetLevel()),
		Vip:        int(req.GetVip()),
		Role:       req.GetRole(),
		Type:       messages2.RoomUserSayMessageType,
		Rich:       "",
		FontColor:  "", //cloudData.FontColor,
	})

	if err != nil {
		global.Log.Errorf("WriteChatHistory err:%v,uid:%d,room:%d,content:%s", err, req.GetUid(), req.GetRoomId(), req.Content)
		resp.IsSucceed = false
	}
	resp.IsSucceed = true
	return
}
